package com.common.help;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Similarity {  
  
  
    public static double Similarity1(String string1, String string2) {  
    	double result = 0; 
    	Map<Character, int[]> vectorMap = new HashMap<Character, int[]>();  
    	
    	int[] tempArray = null;  
        for (Character character1 : string1.toCharArray()) {  
            if (vectorMap.containsKey(character1)) {  
                vectorMap.get(character1)[0]++;  
            } else {  
                tempArray = new int[2];  
                tempArray[0] = 1;  
                tempArray[1] = 0;  
                vectorMap.put(character1, tempArray);  
            }  
        }  
        for (Character character2 : string2.toCharArray()) {  
            if (vectorMap.containsKey(character2)) {  
                vectorMap.get(character2)[1]++;  
            } else {  
                tempArray = new int[2];  
                tempArray[0] = 0;  
                tempArray[1] = 1;  
                vectorMap.put(character2, tempArray);  
            }  
        }
        result = pointMulti(vectorMap) / sqrtMulti(vectorMap);  
        return result;  
    }  
  
    private static double sqrtMulti(Map<Character, int[]> paramMap) {  
        double result = 0;  
        result = squares(paramMap);  
        result = Math.sqrt(result);  
        return result;  
    }  
  
    // 求平方和  
    private static  double squares(Map<Character, int[]> paramMap) {  
        double result1 = 0;  
        double result2 = 0;  
        Set<Character> keySet = paramMap.keySet();  
        for (Character character : keySet) {  
            int temp[] = paramMap.get(character);  
            result1 += (temp[0] * temp[0]);  
            result2 += (temp[1] * temp[1]);  
        }  
        return result1 * result2;  
    }  
  
    // 点乘法  
    private static double pointMulti(Map<Character, int[]> paramMap) {  
        double result = 0;  
        Set<Character> keySet = paramMap.keySet();  
        for (Character character : keySet) {  
            int temp[] = paramMap.get(character);  
            result += (temp[0] * temp[1]);  
        }  
        return result;  
    }  
    public static void main(String[] args) {  
    	String s1 = "浙CQ2132";  
        List<String> list=new ArrayList<>();
        list.add("粤BQ3232");list.add("浙CQ2132");list.add("台FDF358");
        list.add("浙CQ2132");list.add("台CQ2131");list.add("渝ADF358");
        list.add("贵CP2131");list.add("赣ADF359");list.add("粤B3233Q");list.add("浙CQ3132");
        for(String car :list){
        	System.out.println(Similarity1(s1,car));
        } 
    }  
  
} 
